//
//  ZSEncyclopediasHelper.swift
//  creativeassistant
//
//  Created by 灵工邦 on 2025/2/17.
//

import UIKit

class ZSEncyclopediasHelper: NSObject {
    open class func dc_saveEncyclopediasInfo(encyclopediasInfo: ZSAssistantModel) -> Bool {
        do {
            let encoder = JSONEncoder()
            let data = try encoder.encode(encyclopediasInfo)
            let fileURL = URL(fileURLWithPath: self.filePath())
            try data.write(to: fileURL)
            return true
        } catch {
            print("Error saving : \(error)")
            return false
        }
    }
    
    open class func dc_removeeEncyclopediasInfo() -> Bool {
        let fileURL = URL(fileURLWithPath: self.filePath())
        do {
            try FileManager.default.removeItem(at: fileURL)
            return true
        } catch {
            print("Error removing file: \(error)")
            return false
        }
    }
    
    open class func encyclopediasInfo() -> (ZSAssistantModel?) {
        let fileURL = URL(fileURLWithPath: self.filePath())
        if let data = try? Data(contentsOf: fileURL),
           let assistantModel = try? JSONDecoder().decode(ZSAssistantModel.self, from: data) {
            return assistantModel
        }
        return nil
    }

    open class func filePath() -> String {
        return appendFilePath(fileName: "encyclopedias")
    }

    open class func filePath(name: String) -> String {
        return appendFilePath(fileName: name)
    }

    open class func appendFilePath(fileName: String) -> String {
        guard let documentsPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first else {
            return ""
        }
        let filePath = String(format: "%@/%@.archiver", documentsPath, fileName)
        return filePath
    }
}
